import api from '@/services/modules/login.js'

// 微信小程序登录获取code
const wxLogin = () => {
    return new Promise((resolve) => {
        uni.login({
            provider: 'weixin',
            success: res => {
                resolve(res.code)
            }
        })
    })
}

// 根据code获取openid和unionid
const getOpenid = async () => {
    let openid = uni.getStorageSync('openid')
    if(!openid) {
        const code = await wxLogin()
		const res = await api.getOpenIdByCode({
		    code
		})
        const {
            openid,
            unionid,
            session_key
        } = res
        uni.setStorageSync('openid', openid);
        uni.setStorageSync('unionid', unionid);
        uni.setStorageSync('session_key', session_key);
    }
}

export default getOpenid